#! /usr/bin/env python
# -*- coding: utf-8 -*-
import grpc
import time
import sys

sys.path.append("../")
from google.protobuf import json_format
from google.protobuf.util import json_format_proto3_pb2
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from concurrent import futures
from ops import *
from google.protobuf.json_format import MessageToJson, MessageToDict

from rpc import data_pb2_grpc, data_pb2
from config import cfg

engine = create_engine(
    'mysql+pymysql://supervisory:lx@v5.com@123.206.210.251:3307/supervisory_spider?charset=utf8',
    encoding='utf-8', echo=False, pool_recycle=1200, pool_size=100)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))


class Rpc(data_pb2_grpc.DataHandleServicer):

    def clean_mark(self, request, context):
        for i in request.marks:
            db_session().merge(clean_mark(json_format.MessageToDict(i, False, True), request.msg))
        db_session().commit()
        db_session.remove()
        return data_pb2.RpcRes(msg='ok')

    def clean_branch(self, request, context):
        ""
        return data_pb2.RpcRes(msg='test')


if __name__ == '__main__':
    _ONE_DAY_IN_SECONDS = 60 * 60 * 24
    _HOST = cfg.RPCHOST
    _PORT = cfg.RPCPORT


    def serve():
        grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
        data_pb2_grpc.add_DataHandleServicer_to_server(Rpc(), grpcServer)
        grpcServer.add_insecure_port(_HOST + ':' + _PORT)
        grpcServer.start()
        try:
            print("rpc start on port:{}".format(_PORT))
            while True:
                time.sleep(_ONE_DAY_IN_SECONDS)
        except KeyboardInterrupt:
            grpcServer.stop(0)


    serve()
